﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mesoBoard.Web.Core;
using mesoBoard.Data;

namespace mesoBoard.Web.Areas.Admin.Controllers
{
    public class RanksController : mesoBoardAdminController
    {
        public ActionResult Ranks()
        {
            IEnumerable<Rank> Ranks = Repositories.Ranks.GetRanks();
            return View(Ranks);
        }

        [HttpGet]
        public ActionResult EditRank(int RankID)
        {
            return View(Repositories.Ranks.GetRank(RankID));
        }

        [HttpPost]
        public ActionResult EditRank(Rank TheRank)
        {
            if (ModelState.IsValid)
            {
                bool ToTest = Repositories.Ranks.RankExists(TheRank.RankID, TheRank.PostCount);
                if (ToTest && !TheRank.IsRoleRank)
                {
                    ModelState.AddModelError("PostCount", "A rank with " + TheRank.PostCount + " post count already exists");
                    SetError("Validation error");
                    return View(TheRank);
                }

                Repositories.Ranks.UpdateRank(TheRank);
                SetSuccess("Rank updated");
                return RedirectToAction("Ranks");
            }
            else
            {
                SetError("Validation error");
                return View();
            }
        }

        [HttpGet]
        public ActionResult CreateRank()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreateRank(Rank TheRank)
        {
            if (TheRank.IsRoleRank)
                ModelState.Remove("PostCount");
                

            if (ModelState.IsValid)
            {
                if (!TheRank.IsRoleRank && Repositories.Ranks.GetRanks().FirstOrDefault(x => x.PostCount == TheRank.PostCount) != null)
                {
                    ModelState.AddModelError("PostCount", "A rank with " + TheRank.PostCount + " post count already exists");
                    SetError("Validation error");
                    return View();
                }

                Repositories.Ranks.CreateRank(TheRank);
                SetSuccess("Rank created");
                return RedirectToAction("Ranks");
            }
            else
            {
                SetError("Validation error");
                return View();
            }

        }

        public ActionResult DeleteRank(int RankID)
        {
            Repositories.Ranks.DeleteRank(RankID);
            SetSuccess("Rank deleted");
            return RedirectToAction("Ranks");
        }

    }
}
